package com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.zhinenghuacangku_nanjinglu.R;
import com.xiaoxing.zhinenghuacangku_nanjinglu.R2;
import com.xiaoxing.zhinenghuacangku_nanjinglu.di.component.DaggerNanJingLu_JianXiuChuKuComponent;
import com.xiaoxing.zhinenghuacangku_nanjinglu.di.module.NanJingLu_JianXiuChuKuModule;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.contract.NanJingLu_JianXiuChuKuContract;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.model.entity.JianXiuChuKuList;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.presenter.NanJingLu_JianXiuChuKuPresenter;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.adapter.JianXiuChuKuAdapter;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.entity.NanJingLu_JianXiuChuKu;
import com.xiaoxing.zhinenghuacangku_nanjinglu.mvp.ui.entity.OutOfTheLibrary;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static android.support.v7.widget.DividerItemDecoration.VERTICAL;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_NanJingLu_JIAN_XIU_CHU_KU_ACTIVITY)
public class NanJingLu_JianXiuChuKuActivity extends BaseActivity<NanJingLu_JianXiuChuKuPresenter> implements NanJingLu_JianXiuChuKuContract.View, OnRefreshListener, JianXiuChuKuAdapter.ChuKuInterface {

    private static boolean mIsNeedDemo = true;
    private static Disposable mDisposable;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;
    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R2.id.et_shou_ji_hao)
    EditText etShouJiHao;
    @BindView(R2.id.tv_cha_xun)
    TextView tvChaXun;
    String namess = "";
    private JianXiuChuKuAdapter mJianXiuChuKuAdapter;
    private List<OutOfTheLibrary.DataBean> mDataBeanList = new ArrayList<>();
    private List<JianXiuChuKuList> groups = new ArrayList<JianXiuChuKuList>();// 组元素数据列表
    private Map<String, List<String>> children = new HashMap<String, List<String>>();// 子元素数据列表
    private Map<Integer, Integer> mGroupsPosition = new HashMap<>();
    private String mid = "";
    private String instoreBufferId;
    private String mOutStorageListId;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerNanJingLu_JianXiuChuKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .nanJingLu_JianXiuChuKuModule(new NanJingLu_JianXiuChuKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_nan_jing_lu__jian_xiu_chu_ku; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {


        ToolbarUtils.initToolbarTitleBack(this, "检修出库");

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        intervalTransfered();
        chaXunChuKuDan();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mJianXiuChuKuAdapter = new JianXiuChuKuAdapter(getContext(), groups, children, mGroupsPosition));
        //优化嵌套卡顿
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemViewCacheSize(600);
        RecyclerView.RecycledViewPool recycledViewPool = new RecyclerView.RecycledViewPool();
        mRecyclerView.setRecycledViewPool(recycledViewPool);
        mJianXiuChuKuAdapter.setChuKuInterface(this);
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void intervalTransfered() {

        Observable.interval(30, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        chaXunChuKuDan();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void getSearchData() {
        if (etShouJiHao != null)
            if (!TextUtils.isEmpty(getShouJiHao())) {
                clearData();
                searchOutStorageListAutoStore(getShouJiHao(), mSharedPreferencesHelper.getString(BaseConstants.UID));
            }
    }

    @NonNull
    private String getShouJiHao() {
        return etShouJiHao.getText().toString().trim();
    }

    public void clearData() {
        mGroupsPosition.clear();
        children.clear();
        groups.clear();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
    }

    /**
     * 查询待出库列表
     *
     * @param userPhone 手机号
     * @param uid       仓管员登录app的id
     * @return
     */
    private void searchOutStorageListAutoStore(String userPhone, String uid) {

        showLoading();

        String methodName = "GetBadElecMeter";
        SoapParams params = new SoapParams();
//        params.put("userPhone", userPhone);
//        params.put("uid", uid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                try {
                    String result = object.getProperty(methodName + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        List<JianXiuChuKuList> jianXiuChuKuLists = ArmsUtils.parseString2List(result, JianXiuChuKuList.class);
                        mGroupsPosition.clear();
                        children.clear();
                        groups.clear();
                        mEmptyLayout.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);
                        mJianXiuChuKuAdapter.setDataItems(getSampleItems(jianXiuChuKuLists));
                        mJianXiuChuKuAdapter.notifyDataSetChanged();
                        mJianXiuChuKuAdapter.expandAll();
                    } else {
                        clearData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    public List<JianXiuChuKuAdapter.OrderListItem> getSampleItems(List<JianXiuChuKuList> jianXiuChuKuLists) {
        List<JianXiuChuKuAdapter.OrderListItem> items = new ArrayList<>();

        for (int i = 0; i < jianXiuChuKuLists.size(); i++) {

            int groupPosition = items.size();
            mGroupsPosition.put(groupPosition, i);

            JianXiuChuKuList jianXiuChuKuList = jianXiuChuKuLists.get(i);

            groups.add(jianXiuChuKuList);

            items.add(new JianXiuChuKuAdapter.OrderListItem(jianXiuChuKuList));

//            List<String> outList = jianXiuChuKuList.getMeterrfidtag();
//
            List<String> products = new ArrayList<String>();
//
//
//            for (int i1 = 0; i1 < outList.size(); i1++) {
//
//                String outListBean = outList.get(i1);
//
//
//                products.add(outListBean);
//
//                items.add(new JianXiuChuKuAdapter.OrderListItem(groupPosition, outListBean, i1, jianXiuChuKuList.getMaterial()));
//            }

            children.put(String.valueOf(groupPosition), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key

        }
//        items.add(new OutOfTheLibraryAdapter.OrderListItem("", "", "", ""));

        return items;
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void getNanJingLu_JianXiuChuKuDataSuccess(NanJingLu_JianXiuChuKu entityData) {


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null)
            mDisposable.dispose();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mRefreshLayout.finishRefresh();
    }

    @Override
    public void chuKu(String mid, String spid, String spname) {
        chuKU1(mid, spid, spname);
    }

    @Override
    public void queDingNaChu(String mid, String rfidTagStr) {
        confirmGetOutBadElecMeter(mid, rfidTagStr);
    }

    private void confirmGetOutBadElecMeter(String mid, String rfidTagStr) {

        showLoading();
        String methodName = "ConfirmGetOutBadElecMeter";

        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("rfidTagStr", rfidTagStr);

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    chaXunChuKuDan();
                } else {
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    private void chuKU1(String mid, String spid, String spname) {

        showLoading();
        String methodName = "CallAutoMachineGetBadMeterQingDao";

        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("spid", spid);
        params.put("spname", spname);

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    showMessage("正在出库");
                    chaXunChuKuDan();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @OnClick(R2.id.tv_cha_xun)
    public void chaXunChuKuDan() {
        clearData();
        searchOutStorageListAutoStore(getShouJiHao(), mSharedPreferencesHelper.getString(BaseConstants.UID));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {
//                mid = extras.getString("scan_result");
            }
        } else if (resultCode == 102) {
            Bundle extras = data.getExtras();
            if (extras != null) {
//                instoreBufferId = extras.getString("scan_result");
            }
        }
    }


}
